package com.keta.foundation.shiro;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;

public class CaptchaServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static int WIDTH = 110;
	private static int HEIGHT = 50;
	private static int MAX_LENGTH = 4;
	private static int MIN_LENGTH = 4;

	private static ConfigurableCaptchaService captchaService;

	@Override
	public void init() throws ServletException {

		captchaService = new ConfigurableCaptchaService();

		captchaService.setWidth(WIDTH);
		captchaService.setHeight(HEIGHT);

		RandomWordFactory wordFactory = new RandomWordFactory();
		wordFactory.setMaxLength(MAX_LENGTH);
		wordFactory.setMinLength(MIN_LENGTH);

		captchaService.setWordFactory(wordFactory);

		super.init();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 清除缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);

		// 显示类型
		response.setContentType("image/png");

		OutputStream out = response.getOutputStream();
		String patchca = EncoderHelper.getChallangeAndWriteImage(captchaService, "png", out);
		// 将验证码放入Session中
		// request.getSession().setAttribute(request.getSession().getId(),
		// patchca);
		String sessionId = (String) SecurityUtils.getSubject().getSession().getId();
		SecurityUtils.getSubject().getSession().setAttribute(sessionId, patchca);

		out.flush();
		out.close();
	}

	@Override
	public void destroy() {
		captchaService = null;
		super.destroy();
	}

	public static boolean valid(String sessionId, String patchca) {

		String code = (String) SecurityUtils.getSubject().getSession().getAttribute(sessionId);
		// 移除Session中验证码
		SecurityUtils.getSubject().getSession().removeAttribute(sessionId);

		return StringUtils.equalsIgnoreCase(code, patchca);

	}
}
